<?php
/**
 * @title 547. 朋友圈
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[][] $M
     * @return Integer
     */
    function findCircleNum($M) {
        /**
         * @since 2020-08-14 同学数量
         */
        $len = count($M);

        /**
         * @since 2020-08-14 朋友圈数量
         */
        $result = 0;

        /**
         * @since 2020-08-14 遍历查找
         */
        for ($i=0; $i<$len; $i++){
            /**
             * @since 2020-08-14 防止重复, 同学找到后, 移除对应行. 发现同学存在, 则是新的朋友圈
             */
            if(isset($M[$i])){
                // echo "新的朋友圈, i={$i}", PHP_EOL;

                /**
                 * @since 2020-08-14 朋友圈+1
                 */
                $result++;
                $M[$i][$i] = 0;

                /**
                 * @since 2020-08-14 遍历关系
                 */
                $nexts = [$i];
                while($nexts){
                    // echo "朋友关系, [", implode(", ", $nexts) ,"]", PHP_EOL;
                    $nextsTmp = [];

                    /**
                     * @since 2020-08-14 遍历
                     */
                    foreach ($nexts as $row){
                        if(isset($M[$row])){
                            $M[$row][$row] = 0;

                            /**
                             * @since 2020-08-14 查找朋友关系
                             */
                            for($j=0; $j<$len; $j++){
                                /**
                                 * @since 2020-08-14 朋友关系
                                 */
                                if($M[$row][$j] == 1){
                                    $nextsTmp[$j] = $j;

                                    /**
                                     * @since 2020-08-14 防止重复迭代
                                     */
                                    $M[$j][$row] = 0;
                                } else {}
                            }

                            /**
                             * @since 2020-08-14 减少重复迭代
                             */
                            unset($M[$row]);
                        } else {}
                    }

                    /**
                     * @since 2020-08-14 下次循环
                     */
                    $nexts = $nextsTmp;
                }
            } else {}
        }

        /**
         * @return
         */
        return $result;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.14_3.php
 */
$datas = [
    [
        [1,1,0],
        [1,1,0],
        [0,0,1],
    ],
    [
        [1,1,0],
        [1,1,1],
        [0,1,1]
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->findCircleNum($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
